/*
 * 文件名：shopUserController.java
 * 版权：Copyright by hlst
 * 描述：
 * 修改人：liuziyu
 * 修改时间：2016年7月18日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.zcsy.manage.shop.controller.system;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.constants.DistributionConstants;
import com.zcsy.commons.constants.OwnerConstants;
import com.zcsy.commons.constants.ShopConstants;
import com.zcsy.commons.mobile.MobileConfig;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.Globals;
import com.zcsy.manage.model.base.CommonToken;
import com.zcsy.manage.model.base.CommonVerifyCode;
import com.zcsy.manage.model.base.ShopIdAndShopName;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.sms.DlifeSmsService;
import com.zcsy.manage.service.system.IUserService;
import com.zcsy.manage.shop.service.system.ICommonTokenService;
import com.zcsy.manage.shop.service.system.ICommonVerifyCodeService;
import com.zcsy.manage.shop.service.system.ISUserService;

/**
 * @Title: ShopUserController.java
 * @Package： com.zcsy.manage.shop.controller.system 
 * @Description: 商户登录部分控制层
 * @author liuziyu liuziyuwri@foxmail.com
 * @Copyright: 2016 武汉恒数利通软件有限公司 All rights reserved.
 * @date 2016年7月19日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "/shopUser")
public class ShopUserController {

	@Autowired
	ISUserService sUserService;

	@Autowired
	private ICommonTokenService commomTokenService;

	@Autowired
	private IUserService userService;
	
	@Autowired
	private ICommonVerifyCodeService commonVerifyCode;
	

	@Autowired
	private DlifeSmsService dlifeSmsService;

	
	/**
	 * @Description 商户登录
	 * 
	 * @param loginName
	 *            账号名（包括：1、登录名 2、手机号）
	 * @param password
	 *            账号密码
	 * @param platformType
	 *            客户端类型:1.Android;2.iOS
	 * @return
	 * @author liuziyu
	 * @date 2016年7月18日
	 * @see
	 */
	@RequestMapping(value = "login")
	@ResponseBody
	public RequestJson login(String loginName, String password,
			Integer platformType) {
		RequestJson result = new RequestJson();

		try {
			User loginUser = sUserService.shopKeeperLogin(loginName);

			if (loginUser == null) {
				result.setSuccess(false);
				result.setResultCode(ShopConstants.USER_NOT_EXIST);
				result.setMsg("帐号不存在！");
			} else if (loginUser.getState() != ShopConstants.OWNER_USER_STATE) {
				result.setSuccess(false);
				result.setResultCode(ShopConstants.USER_FORBID);
				result.setMsg("该商户已停用！");

			} else if (loginUser.getPwd() != null) {
				if (loginUser.getPwd().equals(password)) {
				    if(null!=loginUser.getHeadimg() ) { 
				        loginUser.setHeadimg(Globals.getImageUrl()+loginUser.getHeadimg());
				    }
					// 获取过期时间间隔30分钟
					String expire = MobileConfig.getMOBILE_TOKEN_EXPIRE();
					Integer expireInteger = Integer.valueOf(expire);

					CommonToken token = new CommonToken();
					Date creatTime = new Date();
					token.setCreateTime(creatTime);
					Calendar cal = Calendar.getInstance();
					cal.setTime(creatTime);
					cal.add(Calendar.MINUTE, expireInteger);
					Date expireTime = cal.getTime();
					token.setExpireTime(expireTime);
					token.setPlatformType(platformType);
					token.setUserType(ShopConstants.SHOP_USER_TYPE);

					// 插入或更新token
					if (loginUser.getLoginname() != null) {
						if (commomTokenService.selectByAccount(loginUser
								.getLoginname()) == null) {
							token.setToken(UniqueNumberUtils
									.get18UniqueNumber());
							token.setId(UniqueNumberUtils.get18UniqueNumber());
							token.setAccount(loginUser.getLoginname());
							commomTokenService.insert(token);
						} else {
							// 让token不失效
							/*
							 * token.setAccount(loginUser.getLoginname());
							 * commomTokenService.updateToken(token);
							 */
							token = commomTokenService
									.selectByAccount(loginUser.getLoginname());
						}
					}

					// 获取商户店铺信息
					List<ShopIdAndShopName> shopInfos = sUserService
							.getShopInfosByUserId(loginUser.getId());

					Map<String, Object> map = new HashMap<String, Object>();
					map.put("user", loginUser);
					map.put("shopInfos", shopInfos);
					map.put("token", token.getToken());

					result.setSuccess(true);
					result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
					result.setMsg("登录成功！");
					result.setObj(map);
				} else {
					result.setSuccess(false);
					result.setResultCode(ShopConstants.RESULT_PASSWORD_FALSE);
					result.setMsg("密码错误！");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setResultCode(ShopConstants.RESULT_EXCEPTION_FALSE);
			result.setMsg("网络异常");
		}

		return result;

	}
	
	/**
	 * @Description 获取验证码<br>
	 * 
	 * @param phone
	 *            手机号
	 * @param operateType 操作类型，1找回密码2绑定手机3验证原手机号
	 * @param token 只有绑定手机才传token
	 * @return resultCode=0:成功 resultCode=其他：失败
	 * @author liuziyu
	 * @date 2016年7月18日
	 * @see 
	 */
	@RequestMapping(value = "getVerification")
	@ResponseBody
	public RequestJson getVerification(String phone,Integer operateType,String token) {

		RequestJson result = new RequestJson();

		//找回密码
		if(operateType == ShopConstants.FIND_PASSWORD){
			List<User> userPhone = userService.selectUserIfPhoneExists(phone, ShopConstants.SHOP_USER_TYPE);
			if(CollectionUtils.isEmpty(userPhone)){
				result.setMsg("手机号不存在!");
				result.setResultCode(ShopConstants.PHONE_NOT_EXIST);
				result.setSuccess(false);
			}else if(userPhone != null && userPhone.size() > 0){
				//如果该用户的验证码记录存在，则删除，重新插入
				CommonVerifyCode code = commonVerifyCode.selectCodeByAccount(userPhone.get(0).getLoginname());
				if (code != null) {
					commonVerifyCode.deleteById(code.getId());
				}
				CommonVerifyCode verifyCode = new CommonVerifyCode();
				
				Map<String, Object> map = this.generateCode(phone);
				verifyCode = (CommonVerifyCode)map.get("verifyCode");
				verifyCode.setUserAccount(userPhone.get(0).getLoginname());
				commonVerifyCode.insert(verifyCode);
				
				result.setMsg("获取成功！");
				result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
				result.setSuccess(true);
				result.setObj(map.get("code"));
				
			}

			//绑定手机
		}else if(operateType == ShopConstants.BOUND_PHONE){
			result = commomTokenService.OrderInteractState(token, result);
			if(result.isSuccess()){
				CommonToken tokenInfo = commomTokenService.selectByToken(token);
				String loginname = tokenInfo.getAccount();
				User user = userService.selectByLoginName(loginname);
				if(user != null){
					if(phone.equals(user.getPhone())){
						result.setMsg("该手机号已绑定，无需再绑定!");
						result.setResultCode(ShopConstants.RESULT_EXSIT_PHONE_FALSE);
						result.setSuccess(false);
					}else{
						//如果该用户的验证码记录存在，则删除，重新插入
						CommonVerifyCode code = commonVerifyCode.selectCodeByAccount(user.getLoginname());
						if (code != null) {
							commonVerifyCode.deleteById(code.getId());
						}
						CommonVerifyCode verifyCode = new CommonVerifyCode();
						
						Map<String, Object> map = this.generateCode(phone);
						verifyCode = (CommonVerifyCode)map.get("verifyCode");
						verifyCode.setUserAccount(user.getLoginname());
						commonVerifyCode.insert(verifyCode);
						
						result.setMsg("获取成功！");
						result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
						result.setSuccess(true);
						result.setObj(map.get("code"));
					}
				}
				
			}
		}else if (operateType == ShopConstants.IDENTIFY_OLD_PHONE) {
			result = commomTokenService.OrderInteractState(token, result);
			if (result.isSuccess()) {
				List<User> userPhone = userService.selectUserIfPhoneExists(phone, ShopConstants.SHOP_USER_TYPE);
				if(CollectionUtils.isEmpty(userPhone)){
					result.setMsg("手机号不存在!");
					result.setResultCode(ShopConstants.PHONE_NOT_EXIST);
					result.setSuccess(false);
				}else if(userPhone != null && userPhone.size() > 0){
					CommonToken tokenInfo = commomTokenService.selectByToken(token);
					String loginname = tokenInfo.getAccount();
					User user = userService.selectByLoginName(loginname);
					if (user != null) {
						if(phone.equals(user.getPhone())){
							//如果该用户的验证码记录存在，则删除，重新插入
							CommonVerifyCode code = commonVerifyCode.selectCodeByAccount(userPhone.get(0).getLoginname());
							if (code != null) {
								commonVerifyCode.deleteById(code.getId());
							}
							CommonVerifyCode verifyCode = new CommonVerifyCode();
							
							Map<String, Object> map = this.generateCode(phone);
							verifyCode = (CommonVerifyCode)map.get("verifyCode");
							verifyCode.setUserAccount(userPhone.get(0).getLoginname());
							commonVerifyCode.insert(verifyCode);
							
							result.setMsg("获取成功！");
							result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
							result.setSuccess(true);
							result.setObj(map.get("code"));
						}else{
							result.setMsg("获取失败！");
							result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
							result.setSuccess(false);
						}
					}
				}
			}
		}
		return result;
	}

	/**
	 * @Description 用于封装获取验证码接口<br>
	 * 
	 * @param phone
	 *            手机号
	 * @return 返回验证码和验证码对象
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年6月27日
	 * @see 
	 */
	public Map<String, Object> generateCode(String phone) {

		// 产生随机代码
		Date date = new Date();
		int count =( new Random()).nextInt(999999);
		if (count<100000) {
			count+=100000;
		}
		
		String content = count+"";
		String sendtime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date);
		dlifeSmsService.sendMsg(phone, content, sendtime);
		
		String expire = MobileConfig.getVERIFYCODE_EXPIRE();
		System.out.println(expire);
		Integer expireInteger = Integer.valueOf(expire);
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MINUTE, expireInteger);
		Date expireTime = cal.getTime();
		
		CommonVerifyCode verifyCode = new CommonVerifyCode();
		verifyCode.setCode(content);
		verifyCode.setCreateTime(date);
		verifyCode.setId(UniqueNumberUtils.get18UniqueNumber());
		verifyCode.setExpireTime(expireTime);
		verifyCode.setPhone(phone);
		verifyCode.setUserType(Constants.BUSINESS_TYPE);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", count);
		map.put("verifyCode", verifyCode);
		return map;
	}
	
	/**
	 * @Method: checkCode
	 * @Description 校验验证码(忘记密码处)
	 * @param phone
	 *            手机号
	 * @param code
	 *            验证码
	 * @return
	 * @author liuziyu liuziyuwri@foxmail.com
	 * @date 2016年6月24日
	 * @see
	 */
	@RequestMapping(value = "checkCode")
	@ResponseBody
	public RequestJson checkCode(String phone, String code) {
		RequestJson result = new RequestJson();

		String loginname = userService.selectLoginNameByPhone(phone);

		// 如果查询不到用户名
		if (StringUtils.isEmpty(loginname)) {
			result.setMsg("手机号未绑定帐号");
			result.setResultCode(ShopConstants.PHONE_NOT_BIND_ACCOUNT);
			result.setSuccess(false);

		} else {
			CommonVerifyCode verifyCode = commonVerifyCode
					.selectCodeByPhone(phone);
			String codes = verifyCode.getCode();
			Date expireTime = verifyCode.getExpireTime();
			Date date = new Date();

			if ((date.compareTo(expireTime)) < 0) {

				if (code.equals(codes)) {
					result.setMsg("校验成功！");
					result.setResultCode(ShopConstants.CODE_VERIFY_SUCCESS);
					result.setSuccess(true);

				} else {
					result.setMsg("输入验证码有误！");
					result.setSuccess(false);
					result.setResultCode(ShopConstants.CODE_IS_FALSE);

				}
			} else {
				result.setMsg("验证码失效，请重新获取");
				result.setSuccess(false);
				result.setResultCode(ShopConstants.CODE_IS_INVALIDE);

			}

		}

		return result;
	}

	/**
	 * token过期返回接口，主要提供给拦截器使用
	 * @return
	 * @author: zt
	 * @date: 2016年6月27日
	 */
	@RequestMapping(value = "tokenIsExpire")
	@ResponseBody
	public RequestJson tokenIsExpire(Integer tokenMessage) {

		RequestJson result = new RequestJson();
		
			if (tokenMessage == ShopConstants.TOKEN_CHANGED) {
				result.setResultCode(tokenMessage);
				result.setMsg("帐号在其他设备登录");
			}
			if (tokenMessage == ShopConstants.TOKEN_EXPIRE) {
				result.setResultCode(tokenMessage);
				result.setMsg("用户授权失效请重新登录");
			}
		
		result.setSuccess(false);
		return result;
	}
	
	 /**
     * @Method: resetPassword 
     * @Description 重置密码
     * @param phone 手机号
     * @param code 验证码
     * @param pwd 新密码
     * @return 
     * @author liuziyu liuziyuwri@foxmail.com
     * @date 2016年6月27日
     * @see 
     */
	@RequestMapping(value = "resetPassword")
	@ResponseBody
	public RequestJson resetPassword(String phone , String code , String pwd) {

		RequestJson result = new RequestJson();

		// 根据手机号查询用户名
		String loginname = userService.selectLoginNameByPhone(phone);

		if (StringUtils.isEmpty(loginname)) {
			result.setMsg("手机号未绑定帐号");
			result.setResultCode(ShopConstants.PHONE_NOT_BIND_ACCOUNT);
			result.setSuccess(false);
			
		} else {
			CommonVerifyCode verifyCode = commonVerifyCode.selectCodeByPhone(phone);
			String codes = verifyCode.getCode();
			Date expireTime = verifyCode.getExpireTime();
			Date date = new Date();

			if ((date.compareTo(expireTime)) < 0) {
				
				if (code.equals(codes)) {
					sUserService.forgetPass(pwd, loginname);
					result.setMsg("成功操作！");
					result.setResultCode(ShopConstants.PHONE_BIND_SUCCESS);
					result.setSuccess(true);
				} else {
					result.setMsg("输入验证码有误！");
					result.setSuccess(false);
					result.setResultCode(ShopConstants.CODE_IS_FALSE);
				}
			} else {
				result.setMsg("验证码失效，请重新获取");
				result.setSuccess(false);
				result.setResultCode(ShopConstants.CODE_IS_INVALIDE);
			}
		}
		return result;
	}
	
	/**
     * @Description 获取个人信息<br>
     * @param token
     * @return 个人信息
     * @author yangfan 373188993@qq.com
     * @date 2016年6月27日
     * @see JDK1.7.0_75
     */
    @RequestMapping(value = "getUserInfo")
    @ResponseBody
    public RequestJson getUserInfo(String token ) {
        
        RequestJson result = new RequestJson();
        
        try {
            //调用方法传入token，无此token返回result为false
            result = commomTokenService.OrderInteractState(token , result);
            
            if (result.isSuccess()) {
                CommonToken tokenInfo = commomTokenService.selectByToken(token);
                String loginname = tokenInfo.getAccount();
                User user = userService.selectByPhone(loginname);
                user.setHeadimg(Globals.getImageUrl()+user.getHeadimg());
                
                result.setSuccess(true);
                result.setResultCode(OwnerConstants.GET_USERINFO_SUCCESS);
                result.setMsg("查看成功！");
                result.setObj(user);
            } else {
                result.setSuccess(false);
                result.setResultCode(OwnerConstants.GET_USERINFO_FALSE);
                result.setMsg("网络异常！");
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常");
        }

        return result;
    }
    
	
}
